package com.yewen.websocket.util;

import com.alibaba.fastjson.JSONObject;
import com.yewen.http.service.EducationCounselorService;
import com.yewen.websocket.message.Message;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import javax.websocket.RemoteEndpoint;
import javax.websocket.Session;
import java.io.IOException;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @Classname WebSocketUtil
 * @Description websocket工具类，提供客户端信息通知发送等功能。
 * @Date 2022/3/25 9:35
 * @Created by TaoVh
 */
@Component
public class WebSocketUtil {


    @Autowired
    private EducationCounselorService educationCounselorService;
    private static WebSocketUtil webSocketUtil;
    @PostConstruct
    public void init(){
        webSocketUtil = this;
        webSocketUtil.educationCounselorService = this.educationCounselorService;
    }
    /**
     * session与用户ID的映射
     */
    private static final Map<Session,String> SESSION_USER_MAP = new ConcurrentHashMap<>();

    private static final Map<String,Session> USER_SESSION_MAP = new ConcurrentHashMap<>();


    private static final Logger logger = LoggerFactory.getLogger(WebSocketUtil.class);
    public static void addSession(Session session,String userID){
//        System.out.println(webSocketUtil.educationCounselorService);
        webSocketUtil.educationCounselorService.inline(userID);
        SESSION_USER_MAP.put(session,userID);
        USER_SESSION_MAP.put(userID,session);
    }
    public static void removeSession(Session session){
        String user = getUserIDBySession(session);
        webSocketUtil.educationCounselorService.offline(user);
        SESSION_USER_MAP.remove(session);
        USER_SESSION_MAP.remove(user);
    }

    public static <T extends Message> void send(Session session, T body,String type){
        if (session == null) {
            logger.error("[send][session 为 null]");
            return;
        }
        RemoteEndpoint.Basic basic = session.getBasicRemote();
        if (basic==null){
            logger.error("[send][session的basic为null]");
            return;
        }
        String completeMessage = buildSendText(body,type);

        try {
            basic.sendText(completeMessage);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    /**
     * @Description 发送消息给指定用户
     * @Author Taovh
     * @Date 2022/3/26 22:32
     * @param userID 指定用户id
     * @param type 消息类型
     * @param body 消息内容
     * @return boolean 是否发送成功
     **/
    public static <T extends Message> boolean send(String userID,String type,T body){
        Session session = USER_SESSION_MAP.get(userID);
        if (session==null){
            logger.error("[send][user({})不存在对应的session]",userID);
            return false;
        }
        send(session,body,type);
        return true;
    }


    /**
     * @Description 构建完整消息
     * @Author Taovh
     * @Date 2022/3/26 20:24
     * @param content
     * @param type
     * @return void
     **/
    public static <T extends Message>String  buildSendText(T content,String type){
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("body",content);
        jsonObject.put("type",type);
        return jsonObject.toString();
    }

    public static Session getSessionByUserID(String userID){
        Session session = USER_SESSION_MAP.get(userID);
        if (session==null){
            logger.error("[getSessionByUserID][{}没有对应的session]",userID);
            return null;
        }
        return session;
    }
    public static String getUserIDBySession(Session session){
        String userID = SESSION_USER_MAP.get(session);
        if (userID.equals("")){
            logger.error("[getUserIDBySession][{}没有对应的userID]",session);
            return null;
        }
        return userID;
    }
}
